<?php
$sourceServer = 'http://localhost';
$base_dir = 'bookpaths';

$bookId = isset($_REQUEST['id']) ? $_REQUEST['id'] : 0;

if($bookId === 0){
    header('Location: '.$sourceServer);
    exit;
}

$exists = check_exists($bookId);
if($exists){
    download($bookId);
} else {
    async_obtain_book($bookId);
    header('Location: http://'.$sourceServer.'/book/download/'.$bookId);
    exit;
}

function check_exists($book_id){
    $disk_path = get_disk_path($book_id);
    return file_exists($disk_path);
}
function get_disk_path($book_id){
    $dir = $book_id % 1000;
    return $base_dir.DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.$book_id;
}
function download($book_id){
    $book_path = file_get_contents(get_disk_path($book_id));
    header('Content-Type: application/force-download');
    header('Content-Disposition: attachment; filename='.basename($book_path));
    header('Content-Length:'.filesize($book_path));
    readfile($book_path);
}
function async_obtain_book($book_id){
    //$book_path = 'd/book/2012/09';
    system('sh download.sh $book_path '.$book_id);
    //http://www.ccs8.cn/book/$book_id.html
}
